﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using GC_MU.BusinessObjects.Representational.Content;
using GC_MU.BusinessObjects.Representational.SiteInfo;
using GC_MU.BusinessObjects.Representational.User;
using GC_MU.Core.Abstractions.Interfaces.Configuration;
using GC_MU.Core.Constants;
using GC_MU.Domain.Abstractions.Interfaces.Services;
using GC_MU.Site.Api.Models;
using Content = GC_MU.BusinessObjects.Content;

namespace GC_MU.Site.Api
{
	public class SiteSettingsController : BaseApiController
	{
		#region Variables

		private readonly IStaticResourcesService _staticResourcesService;

		#endregion

		#region Constructors

		public SiteSettingsController(IApplicationConfiguration appConfiguration, IStaticResourcesService staticResourcesService)
			: base(appConfiguration)
		{
			if (staticResourcesService == null)
				throw new ArgumentNullException(string.Format("staticResourcesService"));
			_staticResourcesService = staticResourcesService;
		}

		#endregion

		#region Actions

		[HttpGet]
		[Route("api/site-settings/get")]
		public ResponseModel<SiteSettingsRepresentation> Get()
		{
			var model = new ResponseModel<SiteSettingsRepresentation>();
			FillSiteSettingsModel(model);
			return ModelState.IsValid ? model : null;
		}

		#endregion

		#region Internal Implementation

		private void FillSiteSettingsModel(ResponseModel<SiteSettingsRepresentation> model)
		{
			if (model == null) return;

			if (model.Response == null)
				model.Response = new SiteSettingsRepresentation();
			if (model.Response.StaticResources == null)
				model.Response.StaticResources = new StaticResourcesRepresentation();
			if (model.Response.Urls == null)
				model.Response.Urls = new UrlSettingsRepresentation();
			if (model.Response.UserInfo == null)
				model.Response.UserInfo = new UserInfoRepresentation
				{
					Name = "Grig",
					Role = "Administrator",
					IsAuthenticated = false
				};

			var bgImageFolder = ApplicationConfiguration.BackgroundImagesFolderPath;
			var serverFolderPath = HttpContext.Current.Server.MapPath(bgImageFolder);
			model.Response.StaticResources.BgImages = (_staticResourcesService.GetImages(bgImageFolder, serverFolderPath,
				Patterns.ImagesExtensions) ?? new List<Content.Image>()).Select(i => new Image
				{
					Src = i.Url,
					Title = i.Title
				}).ToArray();
		}

		#endregion
	}
}
